var express = require('express');
var router = express.Router();
var db = require('../model/index')
const fs = require('fs')

/* 查询图片 */
router.get('/getImg', function (req, res, next) {
  console.log(req.query)
  fs.readFile(`public/${req.query.sort}`, function (err, data) {
    if (err) {
      res.send('读取错误')
    } else {
      res.send(data)
    }
  })
});
//存储图片
router.post('/uploadImg', function (req, res) {
  //接收前台POST过来的base64
  let imgData = JSON.stringify(req.body.base64);
  //过滤data:URL
  let base64Data = imgData.replace(/data:image[^<]*;base64,/, "");
  base64Data = base64Data.replace(" ", "+");
  //转化成二进制数据
  let dataBuffer = Buffer.from(base64Data, 'base64');
  fs.writeFile("public/" + req.body.url, dataBuffer, function (err) {
    if (err) {
      res.send(err);
    } else {
      res.send("保存成功！");
    }
  });
});

module.exports = router;